
using ContractDocumentation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;


namespace ContractDocumentation
{
    class AttributeVisualizer
    {
        static XNamespace xs = "http://www.w3.org/2001/XMLSchema";

        internal static IEnumerable<FrameworkElement> VisualizeAttributes(Context context, XElement parentElement)
        {
            var result = new List<FrameworkElement>();
            foreach (XElement attributeElement in parentElement.Elements(xs + "attribute"))
            {
                result.Add(VisualizeAttributeDeclaration(context, attributeElement));
            }
            // TODO anyAttribute
            return result;
        }

        static FrameworkElement VisualizeAttributeDeclaration(Context context, XElement attributeElement)
        {
            bool isOptional = (string)attributeElement.Attribute("use") != "required";

            Grid grid = new Grid();
            Rectangle rectangle = UIUtils.CreateElementOrAttributeRectangle(isOptional);
            grid.Children.Add(rectangle);
            rectangle.Fill = Brushes.Lavender;

            TextBlock textBlock = new TextBlock();
            textBlock.Style = (Style)context.ResourceDictionary["AttributeTextBlock"];
            grid.Children.Add(textBlock);

            Bold attributeNameBold = new Bold();
            attributeNameBold.Inlines.Add("@ " + (string)attributeElement.Attribute("name"));
            textBlock.Inlines.Add(attributeNameBold);
            if (attributeElement.Attribute("type") != null)
            {
                string type = XmlUtils.GetXName(attributeElement, (string)attributeElement.Attribute("type")).LocalName;
                textBlock.Inlines.Add(new LineBreak());
                textBlock.Inlines.Add(type);
            }
            var q = from simpleTypeElement in attributeElement.Elements(xs + "simpleType")
                    from restrictionElement in simpleTypeElement.Elements(xs + "restriction")
                    select restrictionElement;
            foreach (XElement restrictionElement in q)
            {
                string type = XmlUtils.GetXName(restrictionElement, (string)restrictionElement.Attribute("base")).LocalName;
                textBlock.Inlines.Add(new LineBreak());
                textBlock.Inlines.Add("restriction of " + type);
            }

            grid.Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            return UIUtils.AppendDocumentation(context, grid, XmlUtils.GetXsDocumentation(attributeElement), 
                Math.Max(grid.DesiredSize.Width, 192));
        }

    }
}
